package czopyk.model.persistence.actions;

import java.math.BigDecimal;
import java.util.Map;

import czopyk.model.persistence.ValueExtractor;

public class ChangeVarAction extends CommonAction implements Action {

	private final String var, action, value;
	private Map<String, BigDecimal> variables;
	
	public ChangeVarAction(String var, String action, String value, Map<String, BigDecimal> variables, ValueExtractor ve) {
		super(null, ve);
		if (!"+-*/".contains(action)) {
			throw new IllegalArgumentException("Action must be inluded in + - * /");
		}
		this.var = var;
		this.action = action;
		this.value = value;
		this.variables = variables;
	}

	public void perform() {
		BigDecimal v = variables.get(var);
		BigDecimal arg = ve.getNumber(value);

		if (v == null) {
			throw new IllegalStateException("Variable '" + var
					+ "' not found. Cannot make '... " + action + " " + arg + "'");
		}
		if (arg == null) {
			throw new IllegalStateException("Argument for action '" + var + " " + action
					+ " ...' not found (given value '" + value + "')");
		}

		if ("+".equals(action)) {
			variables.put(var, v.add(arg));
		} else if ("-".equals(action)) {
			variables.put(var, v.subtract(arg));
		} else if ("*".equals(action)) {
			variables.put(var, v.multiply(arg));
		} else if ("/".equals(action)) {
			variables.put(var, v.divide(arg));
		} else {
			throw new IllegalArgumentException("Unknown operator: " + action);
		}
	}
	
}
